#include<stdio.h>
#include"functions.h"
#include<mysql.h>
#include<unistd.h>
extern MYSQL *mysql;
int sys_3_delete(char *query)
{
	char sc;
	int ch_stuid, ch_course;
	char mysql_delete[100];
	scanf("%d %d", &ch_stuid, &ch_course);
	sprintf(mysql_delete, "delete from %s where ch_stuid='%d' and ch_course='%d'", query, ch_stuid, ch_course);
	if(!sys_error(mysql_delete))
		return 0;
	printf("输入回车结束\n");
	scanf("%c", &sc);scanf("%c", &sc);
	return 1;
}
int sys_3_modify(char *table)
{
	char sc;
	int ch_stuid, ch_course, ch_grade;
	char mysql_modify[100];
	printf("请输入您要修改成绩所对应的学生学号和课程ID：");
	scanf("%d %d", &ch_stuid, &ch_course);
	sprintf(mysql_modify, "SELECT ch_grade FROM %s WHERE ch_stuid='%d' and ch_course='%d'", table, ch_stuid, ch_course);
	mysql_query(mysql, mysql_modify);
	MYSQL_RES *res = mysql_store_result(mysql);
	if(mysql_num_rows(res) == 0)
	{	
		fprintf(stderr, "%s\n", mysql_error(mysql));
		printf("无此信息！\n");
		sleep(5);
		return 0;
	}
	else
	{
		printf("当前分数为:");
		MYSQL_ROW row = mysql_fetch_row(res);
		for(unsigned int i = 0; i < mysql_num_fields(res); i++)
		{
			printf("%s",row[i]);
		}
		mysql_free_result(res);
		printf("\n设置最新分数为:");
		scanf("%d", &ch_grade);
		sprintf(mysql_modify, "UPDATE %s SET ch_grade='%d' WHERE ch_stuid='%d' and ch_course='%d'", table, ch_grade, ch_stuid, ch_course);
		if(!sys_error(mysql_modify))
			return 0;
	}
	printf("输入回车结束 ");
	scanf("%c", &sc); scanf("%c", &sc);
	return 1;
}
void sys_3_search(void)
{
	char mysql_insert[100], c;
	int ch_stuid, ch_course, ch_grade;
	printf("请输入要添加的选课信息：学生ID、课程ID、课程成绩,以空格为分隔:");
	scanf("%d %d %d", &ch_stuid ,&ch_course , &ch_grade);
	sprintf(mysql_insert,"SELECT ch_grade FROM ch_class where ch_stuid=%d and ch_course=%d;", ch_stuid, ch_course);
	if(!mysql_query(mysql, mysql_insert))
	{
		MYSQL_RES *result = mysql_store_result(mysql);
		int row = mysql_num_rows(result);
		if(row != 0)
		{
			printf("此课程已选择过！(回车继续)\n");
			scanf("%c", &c);scanf("%c", &c);
			return;
		}
		mysql_free_result(result);
	}
	sprintf(mysql_insert,"SELECT * FROM tb1 where ID=%d", ch_stuid);
	if(!mysql_query(mysql, mysql_insert))
	{
		MYSQL_RES *result = mysql_store_result(mysql);
		int row = mysql_num_rows(result);
		if(row == 0)
		{
			printf("不存在此学生!(回车继续)\n");
			scanf("%c", &c);scanf("%c", &c);
			return;
		}
		mysql_free_result(result);
	}
	sprintf(mysql_insert,"SELECT * FROM class where ID=%d", ch_course);
	if(!mysql_query(mysql, mysql_insert))
	{
		MYSQL_RES *result = mysql_store_result(mysql);
		int row = mysql_num_rows(result);
		if(row == 0)
		{
			printf("不存在此课程!(回车继续)\n");
			scanf("%c", &c);scanf("%c", &c);
			return;
		}
		mysql_free_result(result);
	}
	sprintf(mysql_insert,"INSERT INTO ch_class (ch_stuid,ch_course,ch_grade) values('%d','%d','%d')", ch_stuid, ch_course, ch_grade);
	sys_insert(mysql_insert);
}
